﻿using DotNetUniLodz.HelperClasses;
using DotNetUniLodz.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using System.Web.Mvc;

namespace DotNetUniLodz.Controllers
{
    public class RssController : Controller
    {
        private DotNetULEntities db = new DotNetULEntities();
        
        //
        // GET: /Rss/

        public ActionResult Index()
        {
            int count = 15;
            var syndicationItems = PrepareSyndicationItems(count);

            SyndicationFeed feed = new SyndicationFeed("Grupa .NET UŁ", "News from DotNet.uni.lodz.pl", new Uri("http://dotnet.uni.lodz.pl/main/rss"), syndicationItems);

            return new RssResult(feed);
        }

        private IEnumerable<SyndicationItem> PrepareSyndicationItems(int count)
        {
            var items = db.Articles.OrderByDescending(a => a.Article_id).Take(count);

            foreach (var item in items)
            {
                var content = item.Article_text;
                if (content.Length > 160)
                {
                    content = content.Substring(0, 157) + "...";
                }

                yield return new SyndicationItem(
                    item.Article_title,
                    content,
                    new Uri(String.Format("http://dotnet.uni.lodz.pl/main/Articles/Details/{0}", item.Article_id)),
                    item.Article_id.ToString(),
                    DateTimeOffset.Parse(item.Article_creationDate.ToString()));
            }
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
